package com.lagou.edu.threadlocal;


import com.lagou.edu.pojo.TPMonitor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author 赵虎
 * @date 2021/1/11 2:23 上午
 */
public class TPMonitorThreadLocal {
    private static ConcurrentMap<String, List<Long>> SERVICE_TIME_MAP = new ConcurrentHashMap<>();

    /**
     * 定时线程池
     */
    private static final ScheduledThreadPoolExecutor EXECUTOR_SCHEDULED = ThreadPool.getScheduledThreadPoolExecutor();

    static {
        EXECUTOR_SCHEDULED.scheduleAtFixedRate(() -> SERVICE_TIME_MAP.forEach((key, value) -> System.out.println(getTPMonitor(key, value).toString())), 0, 5, TimeUnit.SECONDS);

        EXECUTOR_SCHEDULED.scheduleAtFixedRate(() -> {
            SERVICE_TIME_MAP = new ConcurrentHashMap<>();
        }, 0, 1, TimeUnit.MINUTES);
    }

    public static void addServiceTime(String key, Long time) {
        if (!SERVICE_TIME_MAP.containsKey(key)) {
            SERVICE_TIME_MAP.put(key, new ArrayList<>());
        }
        SERVICE_TIME_MAP.get(key).add(time);
    }

    public static TPMonitor getTPMonitor(String key, List<Long> list) {
        List<Long> times = list.stream().sorted().collect(Collectors.toList());
        Long tp90 = times.get((int) Math.floor(list.size() * 0.9));
        Long tp99 = times.get((int) Math.floor(list.size() * 0.99));
        return new TPMonitor(key, tp90, tp99, list.size());
    }
}
